package liguo.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.liguo.whoisthespy.R;

import liguo.application.BaseApplication;
import liguo.util.L;


/**
 * 圆形ImageView，可设置最多两个宽度不同且颜色不同的圆形边框。
 * 已扩展为可以设置文字
 * 如果不设置src属性,且设置了seed属性,即可看到效果
 *
 * @author Alan & Damon
 */
public class RoundImageView extends ImageView {
	// 如果只有其中一个有值，则只画一个圆形边框
	private int mBorderOutsideColor = 0;
	private int mBorderThickness = 0;
	private Context mContext;
	private int defaultColor = 0xFFFFFFFF;
	private int mBorderInsideColor = 0;
	// 控件默认长、宽
	private int defaultWidth = 0;
	private int defaultHeight = 0;
	private String seed;
	private Paint mTextPaint;
	public static final int[] COLORS = {
//			0xff44bb66,
//			0xff55ccdd,
//			0xffbb7733,
//			0xffff6655,
//			0xffffbb44,
//			0xff44aaff

			0xffa6937c,
			0xfff29c9f,
			0xff7e6b5a,
			0xffcfa972,
			0xff996c33,
			0xfff29a76,
			0xff313131,
			0xffcce189,
			0xfff19ec2,
			0xfff6b37f,
			0xffbfbfbf,
			0xfffacd89,
			0xff89c997,
			0xff448aca,
			0xffae5da1,
			0xff0068b7,
			0xff009e96,
			0xff638c0b,
			0xff00736d,
			0xff003567,
			0xff005982
	};
	private static final int COLORS_NUMBER = COLORS.length;

	//外边框与内部图片的间距，默认为０
	private int outsideBorderPadding;

	public RoundImageView(Context context) {
		super(context);
		mContext = context;
	}

	public RoundImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		setCustomAttributes(attrs);
	}

	public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		setCustomAttributes(attrs);
	}

	private void setCustomAttributes(AttributeSet attrs) {
		TypedArray a = mContext.obtainStyledAttributes(attrs,
				R.styleable.roundedimageview);
		mBorderThickness = a.getDimensionPixelSize(
				R.styleable.roundedimageview_border_thickness, 0);
		mBorderOutsideColor = a
				.getColor(R.styleable.roundedimageview_border_outside_color,
						defaultColor);
		mBorderInsideColor = a.getColor(
				R.styleable.roundedimageview_border_inside_color, defaultColor);
		outsideBorderPadding = a.getDimensionPixelSize(R.styleable.roundedimageview_border_outside_padding, 0);
		seed = a.getString(R.styleable.roundedimageview_seed);
		a.recycle();
		mTextPaint = new Paint();
		mTextPaint.setColor(Color.WHITE);
		mTextPaint.setTextAlign(Paint.Align.CENTER);
		mTextPaint.setTypeface(BaseApplication.tf);

	}

	@Override
	protected void onDraw(Canvas canvas) {
		Drawable drawable = getDrawable();


		if(seed!=null){
			//值改变后颜色也需要改变
			if(!seed.equals(olds)){
				//没有设置src属性,默认显示纯色
				setImageDrawable(new ColorDrawable(getColorBySeed(seed)));
				drawable = getDrawable();
			}
		}
		if (drawable == null) {
			return;
		}

		if (getWidth() == 0 || getHeight() == 0) {
			return;
		}
		if (defaultWidth == 0) {
			defaultWidth = getWidth();
		}
		if (defaultHeight == 0) {
			defaultHeight = getHeight();
		}
		this.measure(0, 0);
		if (drawable.getClass() == NinePatchDrawable.class){
			return;}
		Bitmap b;
		if(drawable.getClass() != BitmapDrawable.class){
			int w = defaultWidth;
			int h = defaultHeight;
			Config config =
					drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
							: Config.RGB_565;
			b = Bitmap.createBitmap(w,h,config);
			//注意，下面三行代码要用到，否在在View或者surfaceview里的canvas.drawBitmap会看不到图
			Canvas ca = new Canvas(b);
			drawable.setBounds(0, 0, w, h);
			drawable.draw(ca);
		}else{
			b = ((BitmapDrawable) drawable).getBitmap();
		}
		int radius = 0;//半径
		try {
			Bitmap bitmap = b.copy(Config.ARGB_8888, true);



			if (mBorderInsideColor != defaultColor
					&& mBorderOutsideColor != defaultColor) {// 定义画两个边框，分别为外圆边框和内圆边框
				radius = (defaultWidth < defaultHeight ? defaultWidth
						: defaultHeight) / 2 - 2 * mBorderThickness;
				// 画内圆
				drawCircleBorder(canvas, radius + mBorderThickness / 2,
						mBorderInsideColor);
				// 画外圆
				drawCircleBorder(canvas, radius + mBorderThickness
						+ mBorderThickness / 2, mBorderOutsideColor);
			} else if (mBorderInsideColor != defaultColor
					&& mBorderOutsideColor == defaultColor) {// 定义画一个边框
				radius = (defaultWidth < defaultHeight ? defaultWidth
						: defaultHeight) / 2 - mBorderThickness;
				drawCircleBorder(canvas, radius + mBorderThickness / 2,
						mBorderInsideColor);
			} else if (mBorderInsideColor == defaultColor
					&& mBorderOutsideColor != defaultColor) {// 定义画一个边框
				radius = (defaultWidth < defaultHeight ? defaultWidth
						: defaultHeight) / 2 - mBorderThickness;
				drawCircleBorder(canvas, radius + mBorderThickness / 2,
						mBorderOutsideColor);
				radius = radius - outsideBorderPadding;
			} else {// 没有边框
				radius = (defaultWidth < defaultHeight ? defaultWidth
						: defaultHeight) / 2;
			}

			Bitmap roundBitmap = getCroppedRoundBitmap(bitmap, radius);
			canvas.drawBitmap(roundBitmap, defaultWidth / 2 - radius, defaultHeight / 2 - radius, null);
			//canvas.drawBitmap(roundBitmap, roundBitmap.getWidth() / 4, roundBitmap.getHeight() / 4, null);

			if(seed!=null){
				float textSize = oldRadius/1.4142135623731f/1.15f;
				mTextPaint.setTextSize(textSize);
				if(oldRadius!=radius){
					oldRadius=radius;
					textSize = radius/1.4142135623731f/1.15f;
					mTextPaint.setTextSize(textSize);
					Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
					oldbaseline = (defaultHeight - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
				}
				if(!olds.equals(seed)){
					olds = seed;
					if(seed.length()==0){
						subS="";
					}else{
						char c = seed.charAt(0);
						if((c>=65&&c<=90)||(c>=97&&c<=122)){
							subS = (c+"").toUpperCase();
						}else if(seed.length()>2){
							subS = seed.substring(0,2);
						}else{
							subS = seed;
						}
					}
				}

				canvas.drawText(subS,defaultWidth/2f,oldbaseline,mTextPaint);
			}
			roundBitmap.recycle();
			bitmap.recycle();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String olds = "";
	private String subS = "";
	private int oldbaseline = -1;
	private int oldRadius = -1;

	public int getColorBySeed(String seed) {
		if (TextUtils.isEmpty(seed)) {
			return COLORS[0];
		}
		return COLORS[Math.abs(seed.hashCode() % COLORS_NUMBER)];
	}

	/**
	 * 获取裁剪后的圆形图片
	 *
	 * @param radius 半径
	 */
	public Bitmap getCroppedRoundBitmap(Bitmap bmp, int radius) {
		Bitmap scaledSrcBmp;
		int diameter = radius * 2;


		// 为了防止宽高不相等，造成圆形图片变形，因此截取长方形中处于中间位置最大的正方形图片
		int bmpWidth = bmp.getWidth();
		int bmpHeight = bmp.getHeight();
		int squareWidth, squareHeight;
		int x, y;
		Bitmap squareBitmap;
		if (bmpHeight > bmpWidth) {// 高大于宽
			squareWidth = squareHeight = bmpWidth;
			x = 0;
			y = (bmpHeight - bmpWidth) / 2;
			// 截取正方形图片
			squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
					squareHeight);
		} else if (bmpHeight < bmpWidth) {// 宽大于高
			squareWidth = squareHeight = bmpHeight;
			x = (bmpWidth - bmpHeight) / 2;
			y = 0;
			squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth,
					squareHeight);
		} else {
			squareBitmap = bmp;
		}

		if (squareBitmap.getWidth() != diameter
				|| squareBitmap.getHeight() != diameter) {
			scaledSrcBmp = Bitmap.createScaledBitmap(squareBitmap, diameter,
					diameter, true);

		} else {
			scaledSrcBmp = squareBitmap;
		}
		Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(),
				scaledSrcBmp.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		Paint paint = new Paint();
		Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(),
				scaledSrcBmp.getHeight());

		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		canvas.drawARGB(0, 0, 0, 0);
		canvas.drawCircle(scaledSrcBmp.getWidth() / 2,
				scaledSrcBmp.getHeight() / 2, scaledSrcBmp.getWidth() / 2,
				paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(scaledSrcBmp, rect, rect, paint);
		// bitmap回收(recycle导致在布局文件XML看不到效果)
		bmp.recycle();
		squareBitmap.recycle();
		scaledSrcBmp.recycle();
		bmp = null;
		squareBitmap = null;
		scaledSrcBmp = null;
		return output;
	}

	/**
	 * 边缘画圆
	 */
	private void drawCircleBorder(Canvas canvas, int radius, int color) {
		Paint paint = new Paint();
		/* 去锯齿 */
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		paint.setColor(color);
		/* 设置paint的　style　为STROKE：空心 */
		paint.setStyle(Paint.Style.STROKE);
		/* 设置paint的外框宽度 */
		paint.setStrokeWidth(mBorderThickness);
		canvas.drawCircle(defaultWidth / 2, defaultHeight / 2, radius, paint);
	}

	public void setThicknessAndOutColor(int thickness,int color){
		mBorderThickness = thickness;
		mBorderOutsideColor = color;
		mBorderInsideColor = defaultColor;
		invalidate();
	}

	public void setSeed(String seep){
		this.seed = seep;
		invalidate();
	}
}
